package com.application.admin;

import com.application.validate.StatsParamValidator;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台返利统计
 */
@Controller("/admin/statsRebate")
public class StatsRebateController extends BaseController {

    private final String sql_select = "com.application.statsRebate.select";
    private final String sql_from = "com.application.statsRebate.from";
    private final String sql_select2 = "com.application.statsRebate.select2";
    private final String sql_from2 = "com.application.statsRebate.from2";
    private final String sql_select3 = "com.application.statsRebate.select3";
    private final String sql_from3 = "com.application.statsRebate.from3";

    /**
     * 参数：开始时间startDate，结束时间endDate
     */
    @Before(StatsParamValidator.class)
    public void index() {
        splitPage.getQueryParam().put("userid", getAttr("userid"));
        paging(splitPage, sql_select, sql_from);
        List<Record> list = (List<Record>) splitPage.getList();

        splitPage.setExtData(summary());

        renderOk(splitPage);
    }

    private Map<String, String> summary() {
        String fromSql = getSqlByBeetl(sql_from, splitPage.getQueryParam());
        StringBuffer sb = new StringBuffer(1000);
        sb.append("select sum(totalrebate) as amount ");
        sb.append("from (select totalrebate " + fromSql + ") t");

        Record data = Db.findFirst(sb.toString());
        Map<String, String> map = new HashMap<>();
        map.put("total", data.get("amount"));
        return map;
    }

    /**
     * 返利订单列表
     */
    @Before(StatsParamValidator.class)
    public void order() {
//        splitPage.getQueryParam().put("userid", getAttr("userid"));
        paging(splitPage, sql_select2, sql_from2);
        renderOk(splitPage);
    }

    public void orderItem() {
        /*String s = "SELECT a.*, c.`name` as rebate_name from t_order_item a " +
                " left join t_product b on a.product_id = b.id\n" +
                " left join t_rebate c on c.id = b.rebate_id\n" +
                " where a.order_id = ?";
        List<Record> list = Db.find(s, getPara("_query.orderId"));*/
        paging(splitPage, sql_select3, sql_from3);
        renderOk(splitPage);
    }
}
